import { defineStore } from "pinia"

import { MENU_KEY_CONFIG } from "@/assets/common/config.js"

export const useUserStore = defineStore({
    id: "user",
    state: () => {
        return {
            keepAliveList: ['Home'], // 缓存页面的数组
            menuTree: [],
            defaultOpeneds: [],
            userinfo: null,
            activeFirstNavIndex: -1,   // 当前选中的一级菜单索引
            showSubMenu: false, //  是否展示子菜单
            subTitle: "", // 副标题
            menu_id: "", // 菜单ID
            permissions: [], // 权限列表
            roleKeySet: [], // 角色列表
        }
    },
    actions: {
        setInfo(data) {
            this.userinfo = data
        },

        initInfo() {
            this.userinfo = null
        },

        // 菜单
        setMenuTree(menuTree) {
            // 如果一级菜单没有 path，则将子菜单的 path 赋值给一级菜单，如果没有子菜单则将 path = 'Home'
            menuTree.forEach(menu => {
                menu[MENU_KEY_CONFIG.PATH] = this.getMenuPath(menu) || 'Home'
                menu[MENU_KEY_CONFIG.CHILDREN].forEach(children => {
                    children[MENU_KEY_CONFIG.PATH] = this.getMenuPath(children) || ''
                })
            });
            // 添加概况菜单，路径为首页
            menuTree.unshift({
                [MENU_KEY_CONFIG.PATH]: 'Home',
                [MENU_KEY_CONFIG.NAME]: '概况',
                [MENU_KEY_CONFIG.ICON]: 'DataAnalysis',
            })
            this.menuTree = menuTree
            this.defaultOpeneds = [...new Set(this.defaultOpeneds)]
        },

        // 递归获取子菜单第一项的path
        getMenuPath(menu) {
            if (menu[MENU_KEY_CONFIG.PATH]) {
                const path = menu[MENU_KEY_CONFIG.PATH]
                this.defaultOpeneds.push(path)
                return path
            }

            // 子菜单
            if (menu[MENU_KEY_CONFIG.CHILDREN]?.length) {
                const path = this.getMenuPath(menu[MENU_KEY_CONFIG.CHILDREN][0])
                this.defaultOpeneds.push(path)
                return path
            } else {
                return ''
            }

        },

        initMenuTree() {
            this.menuTree = []
            this.defaultOpeneds = []
        },

        // 权限列表
        setPermissions(data) {
            this.permissions = data
        },

        // 初始权限列表
        initPermissions() {
            this.permissions = []
        },

        // 隐藏子菜单
        hiddenSubMenu() {
            this.showSubMenu = false
        },

        // 显示子菜单
        activeSubMenu() {
            this.showSubMenu = true
        },

        // 清空一级菜单选中
        clearCurFirstNavIndex() {
            this.activeFirstNavIndex = -1
            this.hiddenSubMenu()
        },

        // 修改当前激活一级菜单索引
        setCurFirstNavIndex(index) {
            if (typeof index === 'number') {
                if (index > -1) {
                    this.activeFirstNavIndex = index
                } else {
                    throw new Error('argument must be greater than -1. if want clear index please use method clearCurFirstNavIndex.')
                }
            } else {
                throw new Error('argument type must be number.')
            }
        },

        // 修改左侧二级菜单头部标题
        setSubTitle(index) {
            index = index >= 0 ? index : 0
            const title = this.menuTree[index][MENU_KEY_CONFIG.SUB_TITLE] || this.menuTree[index][MENU_KEY_CONFIG.NAME] || ''
            this.subTitle = title
        },

        initSubTitle() {
            this.subTitle = ''
        },

        //插入缓存数组
        addKeepAlive(data) {
            if (!this.keepAliveList.includes(data)) {
                this.keepAliveList.push(data)
            }
        },
        //删除对应缓存字段
        delKeepAlive(data) {
            const index = this.keepAliveList.indexOf(data)
            if (index > -1) {
                this.keepAliveList.splice(index, 1)
            }
        },
        //初始化缓存字段
        initKeepAlive() {
            this.keepAliveList = ['Home']
        },
        // 赋值
        getInclude(data) {
            this.keepAliveList = data
        },
        setRoleKeySet(roleKeySet) {
            this.roleKeySet = roleKeySet
        },
        initRoleKeySet() {
            this.roleKeySet = []
        },
        // 用户退出，清除本地数据
        logout() {
            this.initInfo()
            this.initMenuTree()
            this.initKeepAlive()
            this.initPermissions()
            this.clearCurFirstNavIndex()
            this.initSubTitle()
            this.initRoleKeySet()
            sessionStorage.clear()
            localStorage.clear()
        },
    },
    // 开启数据缓存，在 strategies 里自定义 key 值，并将存放位置由 sessionStorage 改为 localStorage
    // 默认所有 state 都会进行缓存，你可以通过 paths 指定要持久化的字段，其他的则不会进行持久化，如：paths: ['name', 'age'] 替换key的位置
    persist: {
        enabled: true,
        strategies: [
            {
                key: "users",
                storage: localStorage,
            },
        ],
    },
})
